package com.gimi.cloud.bbp.client.service.moreInfo.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gimi.cloud.bbp.client.service.moreInfo.ZmInfoService;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.DateUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.bbp.dao.dao.User.UserDao;
import com.gimi.cloud.bbp.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.bbp.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.bbp.dto.app.moreInfo.MoreInfoDTO;
import com.gimi.cloud.bbp.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.bbp.entity.user.User;

import net.sf.json.JSONObject;

/**
 * @auther loongs
 * @date 2018/1/10  16:49
 */
@Service
public class ZmInfoServiceImpl implements ZmInfoService {
    private static Logger logger = LoggerFactory.getLogger(ZmInfoServiceImpl.class);
    private MoreInfoDao moreInfoDao;
    private SysConfigDao sysConfigDao;
    private InterfacePlatformRequestService requestService;
    private UserDao userDao;
    private final String INTERFACE_PLATFORM_UNIVERSAL_ZMINFO = "interface_platform_universal_zminfo";
    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    @Autowired
    public ZmInfoServiceImpl(MoreInfoDao moreInfoDao, InterfacePlatformRequestService requestService, SysConfigDao sysConfigDao, UserDao userDao) {
        this.moreInfoDao = moreInfoDao;
        this.requestService = requestService;
        this.sysConfigDao = sysConfigDao;
        this.userDao = userDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Response getZmInfo(MoreInfoDTO moreInfoDTO) throws Exception {
        Response response = new Response();
        User user = userDao.queryBy("user_id", moreInfoDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过芝麻信用
        MoreInfoEntity moreInfoEntity = moreInfoDao.getEntityByUserId(moreInfoDTO.getUserId(), 1);
        if (moreInfoEntity != null && moreInfoEntity.getGetdataErrorTimes() >= MAXTIMES) {
            throw new MsgException(ResponseCodeEnum.ZM_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
        }
        //半段是不是新增，true是新增，false已存在
        boolean flag = false;
        if (moreInfoEntity == null) {
            flag = true;
        }

        logger.info("获取芝麻信用评分开始");
        JSONObject config = JSONObject.fromObject(sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_ZMINFO));
        String param = config.getString("param").replace("#openId#", moreInfoDTO.getOpenId());
        logger.info("芝麻信用，请求参数：" + param);
        String result = requestService.sendApiPost(param);
        logger.info("芝麻信用，返回参数：" + result);

        if (flag) {
            moreInfoEntity = new MoreInfoEntity();
            moreInfoEntity.setReportData(result);
            moreInfoEntity.setGetdataTime(new Date());
            moreInfoEntity.setAnalysis("0");

            //user相关
            moreInfoEntity.setAddTime(new Date());
            moreInfoEntity.setAddUname(user.getAddUname());
            moreInfoEntity.setAddUid(user.getUserId());
            moreInfoEntity.setUserId(user.getUserId());

            //1代表芝麻信用
            moreInfoEntity.setDataType("1");
            moreInfoEntity.setGetdataMaxTimes(MAXTIMES);
        }

        //TODO 有效时长，等风控规则
        moreInfoEntity.setReportEffectionBegin(DateUtil.getNow());
        moreInfoEntity.setReportEffectionEnd(DateUtil.getLateYear(1));

        JSONObject resultObject = JSONObject.fromObject(result);
        String code = resultObject.getJSONObject("head").getString("responseCode");
        String msg=null;
        if (code != null && "0000".equals(code)) {
            JSONObject bodyObject = resultObject.getJSONObject("body");
            code = bodyObject.getString("resultCode");
            JSONObject resultData = JSONObject.fromObject(bodyObject.getString("resultData"));
            if (code != null && "BQS000".equals(code)) {
                //如果success为false，就不存在zmScore字段
                if ("true".equals(resultData.getString("success"))) {
                    // moreInfoEntity.setZmScore(StringUtil.toInt(resultData.getString("zmScore")));
                    moreInfoEntity.setGetdata("2");
                }
                if("false".equals(resultData.getString("success"))){
                    msg=resultData.getString("errorMessage");
                }
            }
        }
        logger.info("获取芝麻信用评分结束");

        //如果获得分数失败，分别处理之前有记录和没记录的情况
        if(!"2".equals(moreInfoEntity.getGetdata())){
            if (flag){
                moreInfoEntity.setGetdataErrorTimes(1);
                moreInfoEntity.setGetdata("3");
                moreInfoDao.insertSelective(moreInfoEntity);
            }else {
                moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes()+1);
                moreInfoEntity.setGetdata("3");
                moreInfoEntity.setUpdateUid(user.getUserId());
                moreInfoEntity.setUpdateUname(user.getAddUname());
                moreInfoEntity.setUpdateTime(DateUtil.getNow());
                moreInfoDao.updateByPrimaryKey(moreInfoEntity);
            }
            response.setResponseCode(ResponseCodeEnum.INTERFACE_ERROR , msg);
        }else{
            if (flag){
                moreInfoDao.insertSelective(moreInfoEntity);
            }else {
                moreInfoEntity.setUpdateUid(user.getUserId());
                moreInfoEntity.setUpdateUname(user.getAddUname());
                moreInfoEntity.setUpdateTime(DateUtil.getNow());
                moreInfoDao.updateByPrimaryKey(moreInfoEntity);
            }
            response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }
        return response;
    }
}
